//
//  ShopItem.cpp
//  petgame
//
//  Created by zz on 2018/12/12.
//

#include "ShopItem.hpp"

ShopItem*ShopItem::create(string filename,string shopname,string shopinfo,Vec2 pos,int price,int effect){
    //构建商品对象
    auto shopitem=new ShopItem();
    if(shopitem&&shopitem->init(filename,shopname,shopinfo,pos,price,effect)){
    
        //资源自动释放
        shopitem->autorelease();
        return shopitem;
    }else{
        
        CC_SAFE_DELETE(shopitem);
        return NULL;
    }
}
bool ShopItem::init(string filename,string shopname,string shopinfo,Vec2 pos,int price,int effect){
    
    //初始化商品item的布局和数据
    
    this->_price=price;
    this->_filename=filename;
    this->_shopname=shopname;
    this->_effect=effect;
    this->initWithFile("shopitemss.png");
    this->setScale(0.48);
    this->setPosition(this->getContentSize()/2);
    this->setAnchorPoint(Vec2(0,0));
    auto sp=Sprite::create(filename);
    sp->setScale(0.8);
    sp->setPosition(Vec2(40,this->getContentSize().height/2));
    this->addChild(sp);
    auto label=LabelTTF::create(shopname,"Arial", 30);
    label->setAnchorPoint(Point(0,0.5));
    label->setPosition(Vec2(95,this->getContentSize().height/2+6));
    this->addChild(label);
    auto info=LabelTTF::create(shopinfo, "Arial", 23);
    info->setAnchorPoint(Point(0,0));
    info->setPosition(Vec2(95,this->getContentSize().height/2-40));
    this->addChild(info);
    auto buybtn=MenuItemImage::create("buybtn.png","buybtns.png",CC_CALLBACK_1(ShopItem::buyFun,this));
    buybtn->setScale(1.1);
    buybtn->setPosition(Point(this->getContentSize().width-100,this->getContentSize().height/2));
    auto menu=Menu::create(buybtn,NULL);
    menu->setPosition(Vec2::ZERO);
    this->addChild(menu);
    auto pricelabel=LabelTTF::create(__String::createWithFormat("%i",price)->getCString(),"Arial", 30);

    pricelabel->setPosition(Vec2(this->getContentSize().width-90,this->getContentSize().height/2));
    this->addChild(pricelabel);

    
    return true;
}



int ShopItem::getMoney(){
    //返回商品价格
    return this->_count*this->_price;
}

void ShopItem::toShop(Ref*pSender){
    
}

void ShopItem::buyFun(Ref*pSender){
    
    //执行商品h购买操作
    //获取商品管理类（单例）
    auto shopmanager=ShopManager::getInstance();
    // 判断是否有足够的金币
    if(shopmanager->lessGlod(this->_price)){
        //创建购买信息对象，记录商品的价格等信息
        auto item=ItemInfo::create(this->_filename, this->_shopname, this->_effect);
        //将该对象存储在管理类的商品集合中
        shopmanager->toaddItem(item);
      auto label=(LabelTTF*)(this->getParent()->getParent()->getParent()->getParent()->getChildByTag(999));
    //结算剩余的金币数
        label->setString(__String::createWithFormat("%i",shopmanager->getGlod())->getCString());
    }
}














